package com.ruoyi.message.notice;

import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 握手拦截器（处理会话）
 */
@Component
public class NoticeHandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
                                   ServerHttpResponse response,
                                   WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) {
        // 获取HTTP Session中的用户信息
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            // 通过请求头传
            HttpHeaders headers = request.getHeaders();
            List<String> list = headers.get("receiverId");
            if (!CollectionUtils.isEmpty(list) && !Objects.equals("[object Null]", list.get(0))) {
                attributes.put("receiverId", Long.parseLong(list.get(0)));
            }
            // 通过query传
            String query = servletRequest.getURI().getQuery();
            if (Objects.nonNull(query) && query.contains("receiverId")) {
                String[] split = query.split("&");
                for (String s : split) {
                    if (s.contains("receiverId")) {
                        String[] split1 = s.split("=");
                        attributes.put("receiverId", Long.parseLong(split1[1]));
                    }
                }
            }
        }
        return true;
    }
}